const http=require('http');
const fs=require('fs');
const path=require('path');


function getData(str){
    var arr=str.split('&');
    var obj={};
    for(var i=0;i<arr.length;i++){
        var childArr=arr[i].split('=');
        obj[childArr[0]]=childArr[1];
    }
    return obj;
}

var filePath=path.join(__dirname,'/index.html');
http.createServer((req,res)=>{
    var urlObj=new URL(req.url,"http://localhost:8081/");
    var pathname=urlObj.pathname;
    
    if(pathname=='/'){
        var fileContent=fs.readFileSync(filePath);
        res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
        res.write(fileContent);
        res.end();
    }
    else if(pathname=='/upload'){
        
        //? 用时间戳来命名图片 
        var date=new Date();
    
        var hours=date.getHours();
        var minutes=date.getMinutes();
        var seconds=date.getSeconds();

        var imgPath=path.join(__dirname,`/upload/${hours}-${minutes}-${seconds}.jpg`);

        var str='';
        req.setEncoding('binary');
        req.on("data",(chunk)=>{
            str+=chunk;
        })
        req.on("end",()=>{
            // console.log(str);
            var arr=str.split('\r\n');
            var imgArr=arr.slice(4,arr.length-2);
            var imgStr=imgArr.join('\r\n');
            var buf=Buffer.from(imgStr,"binary");
            // console.log(buf);
            fs.writeFileSync(imgPath,buf,{'encoding':'binary'});
            
        })
    }
    else if(pathname=='/list'){
        var listPath=path.join(__dirname,'/list.html');
        var listContent=fs.readFileSync(listPath);
        res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
        res.write(listContent);
        res.end();
    }
    else if(pathname=='/getlist'){
        var imgList=[];
        var dirPath=path.join(__dirname,'/upload');
        var files=fs.readdirSync(dirPath);
        for(var i=0;i<files.length;i++){
            imgList.push(files[i]);
        }
        res.writeHead(200,{"Content-Type":"text/plain"});
        res.write(JSON.stringify(imgList));
        res.end();
    }
    else if(pathname.indexOf('upload/')>=0){
        // console.log(pathname)
        var picturePath=path.join(__dirname,'/'+pathname);
        console.log(picturePath);
        var imgBuf=fs.readFileSync(picturePath);
        res.writeHead(200,{"Content-Type":'img/png'});
        res.write(imgBuf)
        res.end()
    }
}).listen(8081);
console.log("sever is listening 8081");